var app = getApp();
// 支付倒计时（现版本未使用）
function countdown(count) {
  if (count <= 0) {
    app.busHintRepetition = false;
    return;
  }
  var time = setTimeout(function() {
    count--;
    countdown(count);
  }, 1000)
};
// 指定排序的比较函数
function compare(property) {
  return function(obj1, obj2) {
    var value1 = obj1[property];
    var value2 = obj2[property];
    return value2 - value1; // 降序
  }
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderinfo: [],
    second: 60,
    minute: 1,
    pay: true,
    disabled: false,
    optionKey: "",
    appColor: app.appColor,
    businfo: "",
    isAgree: true,
    dispriceData: app.recivePrice,
    // 提示弹出部分
    animationData: "",
    tabs: ["退票方式", "服务费", "儿童票"],
    activeIndex: 0,
    slideOffset: 0,
    tabW: 0,
    animationDetailed: "",
    topHeight: app.numHeight(),
    // 优惠券活动2020
    DId: '0',
    money: 0,
    // 优惠默认选中第一个
    select: 0,
    workData: "",
    discountsData: [],
    // CouponStatus: 0 可用  1 锁定/未支付   2 已使用  3已过期
    // discountsData: [{
    //     CouponMoeny: 2,
    //     CouponStatus: 0,
    //     ExpiredTime: "2020-01-05",
    //     Id: 1,
    //     IsCanUse: true,
    //     MinUseMoney: 10,
    //     StartUseTime: "2019-12-06",
    //   },
    //   {
    //     CouponMoeny: 10,
    //     CouponStatus: 0,
    //     ExpiredTime: "2020-01-05",
    //     Id: 2,
    //     IsCanUse: true,
    //     MinUseMoney: 11,
    //     StartUseTime: "2019-12-06",
    //   },
    //   {
    //     CouponMoeny: 20,
    //     CouponStatus: 0,
    //     ExpiredTime: "2020-01-05",
    //     Id: 3,
    //     IsCanUse: true,
    //     MinUseMoney: 12,
    //     StartUseTime: "2019-12-06",
    //   }
    // ]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // this.discountsList();
    // this.setData({
    //   discountsData: listData
    // })
    if (app.isRefund) {
      this.setData({
        hintData: ["支持在线退票", "服务费", "不支持儿童购票"],
        refTicket: "支持在线退票",
        workData: app.networkData

      })
    } else {
      this.setData({
        hintData: ["不支持在线退票", "服务费", "不支持儿童购票"],
        refTicket: "暂不支持在线退票",
        workData: app.networkData
      })
    }
    const that = this;
    if (app.optionsP == "" && app.IsFresh) {
      wx.getStorage({
        key: '_topenid',
        success: function(res) {
          that.optionKey = res.data;
        },
        fail(er) {
          that.optionKey = "";
        }
      })
    }

    app.showLoadings();
    var baoId = options.baoId,
      IsInsure = options.insure;
    try {
      wx.getStorage({
        key: 'busLineData',
        success: function(res) {
          if (res.data) {
            that.setData({
              businfo: res.data,
              baoId: baoId,
              IsInsure: IsInsure,
              formId: options.formId,
              model: app.appmodel
            })
            let data = res.data;
            that.orderData(data.GlobalCode, data.NumberOfBus, data.DestinationCode, data.BusDate, data.TerminalName);
          }
        },
      });
      wx.getSystemInfo({
        success: function(res) {
          //设置tab的宽度
          let mtabW = res.windowWidth / 4;
          that.setData({
            tabW: mtabW
          })
        }
      });
    } catch (err) {}
  },

  // 优惠活动2020 ===================================================
  noneD() {
    this.setData({
      select: -1,
      DId: 0,
      payMoney: Number(this.data.orderinfo.ShouldPayment) - 0,
      money: 0
    })
  },
  discountsList: function(k) {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Order/GetUserCoupon',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      dataType: 'json',
      success: function(res) {
        if (!res.data.Result) {
          return
        };
        let dataList = res.data.UserCoupons;
        // 测试数据
        // let dataList = that.data.discountsData;
        // 可用的优惠券列表
        let DList = new Array();
        // 不可用的优惠券数组
        let minList = new Array();
        dataList.forEach(item => {
          // 筛选可用优惠券
          if (item.IsCanUse && item.MinUseMoney <= k) {
            DList.push(item);
          } else {
            minList.push(item)
          }
        })
        // 对可用优惠券按优惠金额降序排序，默认选中第一个优惠券
        var sortArr = [];
        if (DList.length > 0){
          sortArr = DList.sort(compare("CouponMoeny"));
        };
        that.setData({
          discountsData: sortArr.concat(minList),
          select: sortArr.length == 0 ? -1 : 0,
          money: sortArr.length == 0 ? 0 : sortArr[0].CouponMoeny,
          DId: sortArr.length == 0 ? 0 : sortArr[0].Id,
          payMoney: Number(that.data.orderinfo.ShouldPayment) - (sortArr.length == 0 ? 0 : Number(sortArr[0].CouponMoeny))
        })
        let SelectObj = {
          DId: sortArr.length == 0 ? 0 : sortArr[0].Id,
          money: sortArr.length == 0 ? 0 : sortArr[0].CouponMoeny
        }
        wx.setStorage({
          data: SelectObj,
          key: 'selectDId',
        })
      },
      fail: function() {
        console.log("调用失败");
      },
      complete: function(res) {
        that.setData({
          DRes: true
        })
      }
    })
  },
  DSelect(e) {
    let that = this;
    let t = this.data.orderinfo.TicketPayment;
    let minmoney = e.currentTarget.dataset.minmoney;
    let canuse = e.currentTarget.dataset.canuse; 
    if (canuse == false){
      return
    }
    // 订单金额未满
    if (t < minmoney) {
      return
    }
    this.setData({
      select: e.currentTarget.dataset.select,
      DId: e.currentTarget.dataset.id,
      payMoney: Number(this.data.orderinfo.ShouldPayment) - Number(e.currentTarget.dataset.money),
      money: e.currentTarget.dataset.money
    });
  },
  // 优惠活动2020   == END ===================================================

  // 底部提示弹出框
  tabClick: function(e) {
    var that = this;
    var idIndex = e.currentTarget.id;
    var offsetW = e.currentTarget.offsetLeft; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: idIndex,
      slideOffset: offsetW
    });
  },
  bindChange: function(e) {
    var current = e.detail.current;
    var offsetW = current * this.data.tabW; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: current,
      slideOffset: offsetW
    });
  },
  animationkNum: function(num) {
    //创建动画
    var animation = wx.createAnimation({
      // 动画执行时间
      duration: 250,
      timingFunction: "ease",
      // 延迟执行
      delay: 0,
    });
    animation.translate(0, num).step();
    this.setData({
      animationData: animation.export(),
    })
  },
  // 弹入/显示
  showFun: function(e) {
    if (e.currentTarget.dataset.hintindex > 3) {
      this.setData({
        discountShow: true,
      })
    } else {
      this.setData({
        animationShow: true,
        activeIndex: e.currentTarget.dataset.hintindex
      });
    }
    this.animationkNum(-80);
  },
  // 弹出/隐藏
  animtionHiden: function() {
    let that = this;
    this.animationkNum(850);
    setTimeout(function() {
      that.setData({
        animationShow: false,
        // 优惠券弹出框
        discountShow: false,
      });
    }, 200);
  },
  mask: function() {
    if(this.data.DId == 0 && this.data.money == 0){
      let selectObj = {
        DId: 0,
        money: 0
      };
      // 存储用户选择的优惠券
      wx.setStorage({
        data: selectObj,
        key: 'selectDId',
      })
    }else{
      let selectObj = {
        DId: this.data.DId,
        money: this.data.money
      };
      // 存储用户选择的优惠券
      wx.setStorage({
        data: selectObj,
        key: 'selectDId',
      })
    }
    this.animtionHiden();
  },

  bindAgreeChange: function(e) {
    this.setData({
      isAgree: !e.currentTarget.dataset.isagree,
    });
  },

  toWeb() {
    wx.navigateTo({
      url: '/pages/WebHtml/protocol/protocol?index=1',
    })
  },

  orderData: function(GlobalCode, NumberOfBus, DestinationCode, BusDate, TerminalName) {
    var takemanids = "";
    for (var i = 0; i < app.takemaninfo.length; i++) {
      takemanids += app.takemaninfo[i].TakeManId + ",";
    }
    takemanids = takemanids.trim(',');

    var that = this;
    try {
      var isNewUser = app.newUser;
      var optionsToken = app.optionsP;
      // if (app.optionsP == "") {
      //   optionsToken = that.optionKey;
      // }
      if (optionsToken == "" || optionsToken == null) {
        optionsToken = app.optionsToken;
      } else {
        isNewUser = app.IsFresh;
      }
      if (optionsToken == "" || optionsToken == null) {
        optionsToken = that.optionKey;
        if (optionsToken == "" || optionsToken == null) {

        } else {
          isNewUser = app.IsFresh;
        }
      }
      wx.request({
        url: app.serviceurl + 'Order/BuildBusTicketOrder',
        header: {
          Authorization: "Bearer " + app.accesstoken
        },
        data: {
          StartStaionId: GlobalCode,
          BusOfNumber: NumberOfBus,
          DestinationCode: DestinationCode,
          BusDate: BusDate,
          TakeManIDs: takemanids,
          TraderAccount: "hn96520",
          FormId: that.data.formId,
          IsInsure: that.data.IsInsure == 'undefined' ? '' : that.data.IsInsure,
          ProductId: that.data.baoId,
          DestinationName: TerminalName,
          attachInfo: optionsToken,
          isNewUser: isNewUser,
          discountId: app.reciveId,
        },

        dataType: 'json',
        success: function(res) {
          if (!res.data.Result) {
            app.busHint = false;
            that.setData({
              orderinfo: res.data,
              Result: res.data.Result,
              week: "星期" + "日一二三四五六".charAt(new Date(res.data.BusDate).getDay())
            })
            return
          };
          that.discountsList(res.data.TicketPayment);

          app.busHint = true;
          app.orderId = res.data.OrderCode;
          // 存储此次的订单号
          wx.setStorage({
            key: 'setOrderCode',
            data: res.data.OrderCode
          });
          // countdown(300)
          var InsurePayment = res.data.InsureIsFree ? 0 : res.data.InsurePayment;
          var TShouldPayment = parseFloat(res.data.TicketPayment) + parseFloat(InsurePayment) - parseFloat(res.data.DiscountAmount);
          that.setData({
            orderinfo: res.data,
            payMoney: res.data.ShouldPayment,
            TShouldPayment: TShouldPayment,
            Result: true,
            week: "星期" + "日一二三四五六".charAt(new Date(res.data.BusDate).getDay())
          })
        },

        fail: function(err) {
          that.setData({
            Result: false
          })
        },
        complete: function(res) {
          app.hideLoadings();
        }
      })
    } catch (err) {
      that.setData({
        Result: false
      })
      app.hideLoadings();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  openToast: function() {
    wx.showToast({
      title: '支付完成',
      icon: 'success',
      duration: 100
    });
  },

  wxpay: function(e) {
    if (!this.data.isAgree) {
      wx.showModal({
        title: '提示',
        content: '勾选《购票协议》后才可以购票呦~',
        showCancel: false,
        success(res) {}
      })
      return
    }
    app.showLoadings();
    var that = this;
    that.setData({
      pay: false,
      disabled: true
    })
    wx.request({
      url: app.serviceurl + 'Order/PayOrder',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        orderSn: that.data.orderinfo.OrderCode,
        couponId: that.data.DId
      },
      success: function(res) {
        if (res.data.Result) {
          // 是否分享有礼
          app.isGift = res.data.isShowShare;
          if (!res.data.IsNoPay) {
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              package: res.data.package,
              signType: res.data.signType,
              paySign: res.data.paySign,
              success: function(resr) {
                //支付成功
                if (resr.errMsg == "requestPayment:ok") {
                  app.busHintRepetition = false;
                  app.busHint = false;
                  that.openToast();
                  app.orderId = e.currentTarget.dataset.indent;
                  //发送一个通知给后台，告诉用户已经支付完成，让后台检测一下订单状态是否正确更改，根据情况向用户发送即时通知。
                  wx.request({
                    url: app.serviceurl + 'order/NotifyForBusTicketPayFinished',
                    header: {
                      Authorization: "Bearer " + app.accesstoken
                    },
                    data: {
                      orderSn: that.data.orderinfo.OrderCode,
                      package: res.data.package
                    },
                    success: function(res) {
                      //不需要处理
                    }
                  });
                  wx.redirectTo({
                    // url: '../personcenter/orderDetails/orderDetails?decision=true'
                    url: '/pages/applySuccess/applySuccess'
                  })
                }
              },
              fail(err) {}
            })
          } else {
            app.busHintRepetition = false;
            app.busHint = false;
            app.orderId = e.currentTarget.dataset.indent;
            wx.showToast({
              title: '购票成功',
              icon: 'succes',
              duration: 600,
              mask: true
            })
            setTimeout(function() {
              wx.redirectTo({
                url: '../personcenter/orderDetails/orderDetails'
              })
            }, 600)

          }
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail(error) {},
      complete: function(res) {
        var time = setTimeout(function() {
          that.setData({
            disabled: false
          });
        }, 1000)
        app.hideLoadings();
        that.setData({
          pay: false
        })
      }
    });
  },

  skip: function() {
    app.activeIndex = 1;
    wx.redirectTo({
      url: '../personcenter/orderDetails/orderDetails'
    })
    // if (!this.data.Result) {
    //   wx.navigateBack({});
    //   return
    // }

  },

  phoneservice: function(e) {
    wx.makePhoneCall({
      phoneNumber: "96606"
    });
  },
})